<template>
  <!-- 渐变背景层 -->
  <view class="gradient-bg"></view>
  
  <view class="container">
    <!-- 题目筛选 -->
    <view class="filter-bar">
      <picker @change="changeCategory" :value="categoryIndex" :range="categories">
        <view class="picker-item">
          <text>分类: {{ categories[categoryIndex] }}</text>
        </view>
      </picker>
      <picker @change="changeDifficulty" :value="difficultyIndex" :range="difficulties">
        <view class="picker-item">
          <text>难度: {{ difficulties[difficultyIndex] }}</text>
        </view>
      </picker>
    </view>

    <!-- 顶部积分栏 -->
    <view class="points-bar">
      <view class="points-container">
        <uni-icons type="star-filled" size="18" color="#FFD700"></uni-icons>
        <text class="points-text">{{ safeUser.points }}</text>
      </view>
    </view>

    <!-- 题目显示 -->
    <swiper class="question-swiper" 
            :current="currentQuestionIndex"
            @change="swiperChange"
            :disable-touch="submitting || showResult">
      <swiper-item v-for="(question, index) in questions" :key="question._id">
        <view class="question-card"
              @touchstart="cardTouchStart(index)"
              @touchend="cardTouchEnd(index)">
          <view class="card-header">
            <text class="question-number">Q{{ index + 1 }}</text>
            <text class="question-difficulty" :class="getDifficultyClass(question.difficulty)">
              {{ question.difficulty }}
            </text>
          </view>
          <text class="question-title">{{ question.content }}</text>
          
          <radio-group @change="selectAnswer($event, index)">
            <label v-for="(value, key) in question.options" :key="key" 
                   class="option-item" 
                   :class="{'selected': answers[index] === key}">
              <radio :value="key" :checked="answers[index] === key" 
                     :disabled="submitting || showResult" color="#4a90e2" />
              <text class="option-text">{{ key }}. {{ value }}</text>
            </label>
          </radio-group>

          <!-- 结果显示 -->
          <view v-if="showResult && currentQuestionIndex === index" class="result-box">
            <text class="result-text" :class="{'correct': isCorrect, 'wrong': !isCorrect}">
              {{ isCorrect ? '回答正确！' : '回答错误' }}
            </text>
            <view v-if="!isCorrect" class="explanation-box">
              <text class="explanation-title">正确答案: {{ question.answer }}</text>
              <text class="explanation-text">{{ question.explanation || '暂无详细解析' }}</text>
              <button class="save-btn" @click="addToWrongBook(question, index)">
                <uni-icons type="star-filled" size="16" color="#FFD700"></uni-icons>
                <text>加入错题本</text>
              </button>
              <button class="cancel-btn" @click="nextQuestion">继续下一题</button>
            </view>
          </view>
        </view>
      </swiper-item>
    </swiper>

    <!-- 加载状态 -->
    <view v-if="loading" class="loading-state">
      <view class="spinner"></view>
      <text>题目加载中...</text>
    </view>

    <!-- 空状态 -->
    <view v-if="!loading && !questions.length" class="empty-state">
      <image src="/static/images/empty-questions.png" mode="aspectFit" class="empty-image"></image>
      <text class="empty-text">暂无题目</text>
      <text class="empty-tip">点击下方按钮刷新试试</text>
      <button class="refresh-btn" @click="loadQuestions">刷新题目</button>
    </view>

    <!-- 底部操作栏 -->
    <view class="action-bar">
      <button class="history-btn" @click="goToWrongBook">
        <uni-icons type="calendar-check" size="18" color="#fff"></uni-icons>
        <text>答题记录</text>
      </button>
      
      <button class="submit-btn" 
              :class="{
                'active': answers[currentQuestionIndex],
                'disabled': !answers[currentQuestionIndex] || submitting || showResult
              }"
              @click="submitAnswer">
        <text v-if="submitting">提交中...</text>
        <text v-else>提交答案</text>
      </button>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      user: {},
      questions: [],
      answers: [],
      loading: false,
      submitting: false,
      currentQuestionIndex: 0,
      showResult: false,
      isCorrect: false,
      loadStatus: 'more',
      categories: ['全部'],
      categoryIndex: 0,
      difficulties: ['全部'],
      difficultyIndex: 0
    };
  },
  onLoad() {
    this.loadUserData();
    this.loadFilterOptions();
    this.loadQuestions();
  },
  onShow() {
    this.getUserPoints();
    this.checkPendingPk();
  },
  computed: {
    safeUser() {
      return this.user || { points: 0 };
    }
  },
  methods: {
    loadUserData() {
      this.user = uni.getStorageSync('user') || {};
      if (!this.user.id) {
        uni.navigateTo({ url: '/pages/student/login' });
      }
    },
    async loadFilterOptions() {
      try {
        const res = await uniCloud.callFunction({
          name: 'getQuestionFilters'
        });
        if (res.result.code === 0) {
          this.categories = ['全部', ...res.result.data.categories];
          this.difficulties = ['全部', ...res.result.data.difficulties];
        } else {
          uni.showToast({ title: '加载筛选选项失败', icon: 'none' });
        }
      } catch (e) {
        uni.showToast({ title: '加载筛选选项失败', icon: 'none' });
      }
    },
    changeCategory(e) {
      this.categoryIndex = e.detail.value;
      this.loadQuestions();
    },
    changeDifficulty(e) {
      this.difficultyIndex = e.detail.value;
      this.loadQuestions();
    },
    getDifficultyClass(difficulty) {
      const difficultyMap = {
        '简单': 'easy',
        '中等': 'medium',
        '困难': 'hard'
      };
      return difficultyMap[difficulty] || '';
    },
    cardTouchStart(index) {
      this.animate(`.question-card:nth-child(${index + 1})`, [
        { transform: 'translateY(0)' },
        { transform: 'translateY(-2px)' }
      ], 100);
    },
    cardTouchEnd(index) {
      this.animate(`.question-card:nth-child(${index + 1})`, [
        { transform: 'translateY(-2px)' },
        { transform: 'translateY(0)' }
      ], 150);
    },
    async getUserPoints() {
      try {
        const res = await uniCloud.callFunction({
          name: 'getUserPoints',
          data: { user_id: this.user.id }
        });
        if (res.result.code === 0) {
          this.user.points = res.result.data.points;
          uni.setStorageSync('user', this.user);
        }
      } catch (e) {
        console.error('获取积分失败:', e);
      }
    },
    async loadQuestions() {
      this.loading = true;
      try {
        const category = this.categories[this.categoryIndex] === '全部' ? '' : this.categories[this.categoryIndex];
        const difficulty = this.difficulties[this.difficultyIndex] === '全部' ? '' : this.difficulties[this.difficultyIndex];
        const res = await uniCloud.callFunction({
          name: 'getQuestions',
          data: { 
            category, 
            difficulty, 
            limit: 10 
          }
        });
        if (res.result.code === 0) {
          this.questions = res.result.data;
          this.answers = new Array(this.questions.length).fill('');
          this.currentQuestionIndex = 0;
          this.showResult = false;
        } else {
          uni.showToast({ title: res.result.msg || '加载题目失败', icon: 'none' });
        }
      } catch (e) {
        uni.showToast({ title: '加载题目失败', icon: 'none' });
      } finally {
        this.loading = false;
      }
    },
    swiperChange(e) {
      this.currentQuestionIndex = e.detail.current;
      this.showResult = false;
    },
    selectAnswer(e, index) {
      this.$set(this.answers, index, e.detail.value);
    },
    async submitAnswer() {
      if (!this.answers[this.currentQuestionIndex]) {
        uni.showToast({ title: '请选择答案', icon: 'none' });
        return;
      }
      this.submitting = true;
      try {
        const question = this.questions[this.currentQuestionIndex];
        const submitData = {
          question_id: question._id,
          user_answer: this.answers[this.currentQuestionIndex],
          content: question.content,
          options: question.options,
          correct_answer: question.answer,
          explanation: question.explanation
        };

        const res = await uniCloud.callFunction({
          name: 'submitAnswers',
          data: { user_id: this.user.id, answers: [submitData] }
        });

        if (res.result.code === 0) {
          const { points, totalPoints, correctCount } = res.result.data;
          this.isCorrect = correctCount === 1;
          this.showResult = true;
          uni.showToast({
            title: this.isCorrect ? `回答正确，获得 ${points} 积分` : '回答错误',
            icon: this.isCorrect ? 'success' : 'none',
            duration: 1500
          });
          this.user.points = totalPoints;
          uni.setStorageSync('user', this.user);
          if (this.isCorrect) {
            setTimeout(() => this.nextQuestion(), 1500);
          }
        } else {
          uni.showToast({ title: res.result.msg || '提交失败', icon: 'none' });
        }
      } catch (e) {
        uni.showToast({ title: '提交失败，网络错误', icon: 'none' });
      } finally {
        this.submitting = false;
      }
    },
    async addToWrongBook(wrong, index) {
      try {
        const res = await uniCloud.callFunction({
          name: 'addToWrongBook',
          data: {
            user_id: this.user.id,
            wrong_questions: [wrong]
          }
        });
        if (res.result.code === 0) {
          uni.showToast({ title: '已加入错题本', icon: 'success' });
          this.nextQuestion();
        } else {
          uni.showToast({ title: '加入错题本失败', icon: 'none' });
        }
      } catch (e) {
        uni.showToast({ title: '加入错题本失败', icon: 'none' });
      }
    },
    nextQuestion() {
      if (this.currentQuestionIndex < this.questions.length - 1) {
        this.currentQuestionIndex++;
      } else {
        this.loadQuestions();
      }
      this.showResult = false;
    },
    goToWrongBook() {
      uni.navigateTo({
        url: '/pages/student/answer_history'
      });
    },
    animate(selector, keyframes, duration) {
      const query = uni.createSelectorQuery().in(this);
      query.select(selector).boundingClientRect();
      query.exec(res => {
        if (res[0]) {
          res[0].animate(keyframes, {
            duration,
            fill: 'forwards'
          });
        }
      });
    },
    async checkPendingPk() {
      try {
        const res = await uniCloud.callFunction({
          name: 'checkPendingPk',
          data: { user_id: this.user.id }
        });
        if (res.result.code === 0 && res.result.data.pk_id) {
          uni.showModal({
            title: '挑战请求',
            content: `来自 ${res.result.data.challenger_name} 的挑战，是否接受？`,
            success: async (modalRes) => {
              if (modalRes.confirm) {
                await uniCloud.callFunction({
                  name: 'acceptPk',
                  data: { pk_id: res.result.data.pk_id, user_id: this.user.id, accept: true }
                });
                uni.navigateTo({ url: '/pages/student/pk' });
              } else {
                await uniCloud.callFunction({
                  name: 'acceptPk',
                  data: { pk_id: res.result.data.pk_id, user_id: this.user.id, accept: false }
                });
              }
            }
          });
        }
      } catch (e) {
        console.error('检查PK请求失败:', e);
      }
    }
  }
};
</script>

<style lang="scss" scoped>
$primary-color: #4a90e2;
$secondary-color: #5aa1ff;
$accent-color: #FFD700;
$success-color: #4CAF50;
$error-color: #FF5252;
$text-primary: #333;
$text-secondary: #666;
$text-light: #fff;
$bg-light: rgba(255,255,255,0.95);
$border-color: rgba(0,0,0,0.08);

.gradient-bg {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 40vh;
  background: linear-gradient(135deg, $primary-color 0%, $secondary-color 100%);
  z-index: 0;
  border-radius: 0 0 30% 30%;
}

.container {
  position: relative;
  padding: 20rpx 20rpx 120rpx;
  min-height: 100vh;
  z-index: 1;
  display: flex;
  flex-direction: column;
}

.filter-bar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20rpx;
  
  .picker-item {
    background: $bg-light;
    padding: 16rpx 24rpx;
    border-radius: 20rpx;
    font-size: 28rpx;
    color: $text-primary;
  }
}

.points-bar {
  padding: 16rpx 24rpx;
  display: flex;
  justify-content: flex-end;
  
  .points-container {
    display: flex;
    align-items: center;
    padding: 8rpx 16rpx;
    background: rgba(255, 215, 0, 0.1);
    border-radius: 20rpx;
    transition: all 0.2s ease;
    
    &:active {
      background: rgba(255, 215, 0, 0.2);
      transform: scale(0.95);
    }
    
    .points-text {
      font-size: 28rpx;
      font-weight: 600;
      color: #333;
      margin-left: 8rpx;
    }
  }
}

.question-swiper {
  flex: 1;
  height: calc(100vh - 300rpx);
}

.question-card {
  background: $bg-light;
  border-radius: 16rpx;
  padding: 24rpx;
  margin: 0 10rpx;
  box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.03);
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16rpx;
    
    .question-number {
      font-size: 28rpx;
      font-weight: 700;
      color: $primary-color;
    }
    
    .question-difficulty {
      font-size: 24rpx;
      padding: 4rpx 12rpx;
      border-radius: 20rpx;
      
      &.easy {
        background: rgba($success-color, 0.1);
        color: $success-color;
      }
      &.medium {
        background: rgba(#FF9800, 0.1);
        color: #FF9800;
      }
      &.hard {
        background: rgba($error-color, 0.1);
        color: $error-color;
      }
    }
  }
  
  .question-title {
    font-size: 30rpx;
    font-weight: 500;
    color: $text-primary;
    line-height: 1.6;
    margin-bottom: 24rpx;
  }
}

.option-item {
  display: flex;
  align-items: center;
  padding: 20rpx;
  margin-bottom: 16rpx;
  border-radius: 12rpx;
  background: #f9f9f9;
  transition: all 0.2s ease;
  
  &.selected {
    background: rgba($primary-color, 0.08);
    border: 1rpx solid rgba($primary-color, 0.3);
  }
  
  radio {
    transform: scale(0.9);
    margin-right: 16rpx;
  }
  
  .option-text {
    font-size: 28rpx;
    color: $text-primary;
    flex: 1;
  }
}

.result-box {
  margin-top: 20rpx;
  padding: 20rpx;
  
  .result-text {
    font-size: 28rpx;
    font-weight: 500;
    &.correct {
      color: $success-color;
    }
    &.wrong {
      color: $error-color;
    }
  }
  
  .explanation-box {
    background: #f9f9f9;
    border-radius: 12rpx;
    padding: 20rpx;
    margin-top: 20rpx;
    
    .explanation-title {
      font-size: 26rpx;
      font-weight: 500;
      color: $primary-color;
      margin-bottom: 12rpx;
    }
    
    .explanation-text {
      font-size: 26rpx;
      color: $text-secondary;
      line-height: 1.6;
    }
    
    .save-btn, .cancel-btn {
      background: rgba($accent-color, 0.1);
      color: darken($accent-color, 10%);
      border-radius: 50rpx;
      height: 70rpx;
      font-size: 28rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-top: 20rpx;
      
      uni-icons {
        margin-right: 8rpx;
      }
    }
    
    .cancel-btn {
      background: #f0f0f0;
      color: $text-secondary;
      margin-left: 20rpx;
    }
  }
}

.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 80rpx 0;
  
  .spinner {
    width: 48rpx;
    height: 48rpx;
    border: 4rpx solid rgba($primary-color, 0.1);
    border-top-color: $primary-color;
    border-radius: 50%;
    animation: spin 1s linear infinite;
    margin-bottom: 20rpx;
  }
  
  text {
    font-size: 28rpx;
    color: $text-secondary;
  }
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 60rpx 0;
  text-align: center;
  
  .empty-image {
    width: 300rpx;
    height: 300rpx;
    opacity: 0.7;
    margin-bottom: 30rpx;
  }
  
  .empty-text {
    font-size: 32rpx;
    color: $text-secondary;
    margin-bottom: 12rpx;
  }
  
  .empty-tip {
    font-size: 26rpx;
    color: #999;
    margin-bottom: 30rpx;
  }
  
  .refresh-btn {
    background: $primary-color;
    color: $text-light;
    border-radius: 50rpx;
    padding: 0 40rpx;
    height: 70rpx;
    font-size: 28rpx;
  }
}

.action-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: $bg-light;
  padding: 20rpx;
  display: flex;
  justify-content: space-between;
  box-shadow: 0 -4rpx 12rpx rgba(0,0,0,0.05);
  z-index: 10;
  
  .history-btn {
    background: linear-gradient(45deg, #9C27B0, #AB47BC);
    color: $text-light;
    border-radius: 50rpx;
    height: 80rpx;
    width: 200rpx;
    font-size: 28rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    
    uni-icons {
      margin-right: 8rpx;
    }
  }
  
  .submit-btn {
    background: #e0e0e0;
    color: $text-secondary;
    border-radius: 50rpx;
    height: 80rpx;
    flex: 1;
    margin-left: 20rpx;
    font-size: 32rpx;
    font-weight: 500;
    transition: all 0.3s ease;
    
    &.active {
      background: linear-gradient(45deg, $primary-color, $secondary-color);
      color: $text-light;
      box-shadow: 0 4rpx 16rpx rgba($primary-color, 0.3);
    }
    
    &.disabled {
      opacity: 0.7;
    }
  }
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

@media (min-width: 768px) {
  .container {
    max-width: 750px;
    margin: 0 auto;
  }
  
  .question-card {
    padding: 32rpx;
  }
  
  .option-item {
    padding: 24rpx;
  }
}
</style>